package yr.website

import grails.converters.JSON
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest

import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

class ApplyController {
    def applyService

    def add() {
        def data = [:]
        def apply = new Apply()
        bindData(apply, params, [exclude: ['filePath', 'code']])
        def logoImg = request.getFile("filePath")
        def filePath = request.getSession().getServletContext().getRealPath("word")
        File f = new File(filePath)
        if (!f.exists()) {
            f.mkdirs()
        }
        def logoName = logoImg.getOriginalFilename()
        def fileSuffix = logoName.substring(logoName.lastIndexOf("."))
        def fileName = "${new Date().format("yyyyMMdd")} ${apply.job} ${apply.username}${fileSuffix}"
        def file = new File("${filePath}/${fileName}")
        logoImg.transferTo(file)
        def flag = applyService.add(fileName, apply)
        if (flag) {
            data << [str: "0"]
        } else {
            data << [str: "1"]
        }
        render data as JSON
    }

    def getAll() {
        def data = [:]
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd")
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def job = "${params.job ?: ''}"
        def state = "${params.state ?: ''}"
        def startime = "${params.start ?: ''}"
        def endtime = "${params.end ?: ''}"
        def a = Apply.createCriteria()
        def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
            and {
                if (!job.isEmpty()) {
                    ilike("job", "%${job}%")
                }
                if (!state.isEmpty()) {
                    if (state == "true") {
                        eq("state", true)
                    } else {
                        eq("state", false)
                    }
                }
                if (!startime.isEmpty()) {
                    ge("applyDate", new Date(Long.parseLong(startime)))
                }
                if (!endtime.isEmpty()) {
                    def start = sdf2.format(new Date(Long.parseLong(endtime)))
                    Date end = sdf1.parse(start + " 23:59:59")
                    le("applyDate", end)
                }
            }
            order("applyDate", "desc")
        }
        def b = Apply.createCriteria()
        def length = b.get {
            and {
                if (!job.isEmpty()) {
                    ilike("job", "%${job}%")
                }
                if (!state.isEmpty()) {
                    if (state == "true") {
                        eq("state", true)
                    } else {
                        eq("state", false)
                    }
                }
                if (!startime.isEmpty()) {
                    ge("applyDate", new Date(Long.parseLong(startime)))
                }
                if (!endtime.isEmpty()) {
                    def start = sdf2.format(new Date(Long.parseLong(endtime)))
                    Date end = sdf1.parse(start + " 23:59:59")
                    le("applyDate", end)
                }
            }
            projections {
                rowCount()
            }
        }
        if (list) {
            data << [statuCode: "0", errMsg: "0", data: list, total: length]
        } else {
            data << [statuCode: "1", errMsg: "1"]
        }
        render data as JSON
    }
    /**
     * 简历下载
     * @return
     */
    def download() {
        def fileName = "${params.fileName}"
//        def fileName = URLEncoder.encode(name).toString()
        def id = Integer.parseInt("${params.id}")
        def apply = Apply.findById(id)
        if (apply.state) {
            applyService.changeState(apply)
        }
        def wordFilePath = request.getSession().getServletContext().getRealPath("word")
        def wordFile = new File("${wordFilePath}/${fileName}")
        def inputStream
        try {
            long wordFileSize = wordFile.size()
            response.reset()
            response.setCharacterEncoding("utf-8")
            response.setContentType("application/x-download")
            response.setHeader("Accept-Ranges", "bytes")
            response.setHeader("Content-Length", "${wordFileSize}")
//            response.setHeader("Content-Disposition", "attachment;filename=\"${new String(fileName.getBytes("utf-8"), "iso-8859-1")}\"")
            response.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"))
            inputStream = new FileInputStream(wordFile.getPath())
            long position = 0
            if (null != request.getHeader("Range")) {
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT)
                try {
                    position = Long.parseLong(request.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""))
                } catch (NumberFormatException e) {
                    position = 0
                    e.printStackTrace()
                }
            }

            def outputStream = response.getOutputStream()
            response.setHeader("Content-Range", "bytes ${position}-${wordFileSize - 1}/${wordFileSize}")
            inputStream.skip(position)

            byte[] buffer = new byte[10240]
            int length
            while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, length)
            }
            outputStream.flush()
        } finally {
            if (inputStream != null) {
                inputStream.close()
            }
        }
    }
}
